const socketServer = require('socket.io');

let room = [];
let user = []
let totalConnect = 0;

const connect = () => {
  totalConnect += 1;
  console.log(`总连接数${totalConnect}`);
};

const newRoom = (data,callback, socket) => {
  room[data] ? room[data].add(socket) : room[data] = new Set([socket]);
  user[socket.id] = data;
  callback(`房间已创建 当前在线${room[data].size}人`);
  console.log(room);
};

const toUpdate = (home,data) => {
  console.log(JSON.stringify(home)+' '+JSON.stringify(data));
  for (const toSocket of room[home]){
    console.log(toSocket.id);
    toSocket.emit('update',data);
  }
};

const exitRoom = (socket) => {
  const room_id = user[socket.id];
  if (room[room_id].has(socket)) room[room_id].delete(socket);
  console.log(room);
  totalConnect -= 1;
  console.log(`总连接数${totalConnect}`);
};

module.exports = function (server) {
    const io = socketServer.listen(server);
    io.on('connection', socket => {
        connect();

        socket.on('newRoom',(data,callback) => {
          newRoom(data, callback, socket)});

        socket.on('toUpdate',(home,data) => {
          toUpdate(home, data)});

        socket.on('disconnect',() => {
          exitRoom(socket)});
    });
};
